<?php

namespace app\service;

use app\model\ModuleModel;
use app\tool\SingletonTrait;

class ModuleService
{
    use SingletonTrait;

    protected $moduleData = [];
    protected $byId = [];
    protected $byCode = [];

    public function __construct()
    {
        $this->moduleData = ModuleModel::select();
        $this->byId = $this->moduleData->column(null, 'id');
        $this->byCode = $this->moduleData->column(null, 'code');
    }

    public function byId(int $moduleId, string $column = null)
    {
        if (!empty($column)) {
            return $this->byId[$moduleId][$column] ?? null;
        }
        return $this->byId[$moduleId] ?? null;
    }

    public function byCode(string $moduleCode, string $column = null)
    {
        if (!empty($column)) {
            return $this->byCode[$moduleCode][$column] ?? null;
        }
        return $this->byCode[$moduleCode] ?? null;
    }

    /**
     * @param array $moduleCodeList
     * @param bool $exclude
     * @param string|null $implodeKey
     * @return array|string
     */
    public function byCodeMap(array $moduleCodeList, bool $exclude = false, string $implodeKey = null)
    {
        $res = [];
        if (!$exclude) {
            foreach ($moduleCodeList as $code) {
                if (isset($this->byCode[$code])) {
                    $res[$code] = $this->byCode[$code];
                }
            }
        } else {
            foreach ($this->byCode as $code => $item) {
                if (in_array($code, $moduleCodeList)) {
                    $res[$code] = $item;
                }
            }
        }
        if (!empty($implodeKey)) {
            return implode(',', array_column($res, $implodeKey));
        }
        return $res;
    }
}